package controller.student;

import service.impl.StudentServiceImpl;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import util.BaseResult;
import vo.GetStudentVO;

@WebServlet(urlPatterns = "/getStudent")
public class StudentServlet extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {

            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");

            String name = req.getParameter("name");

            StudentServiceImpl service = new StudentServiceImpl();
            List<GetStudentVO> list = service.getAll(name);

            BaseResult<List<GetStudentVO>> result = BaseResult.success(list);

            String jsonResponse = objectMapper.writeValueAsString(result);
            resp.getWriter().write(jsonResponse);

        } catch (Exception e) {
            logger.error("获取学生信息错误", e);

            BaseResult<Void> errorResult = BaseResult.failed(500, "加载学生信息失败: " + e.getMessage());

            resp.setContentType("application/json;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            String jsonError = objectMapper.writeValueAsString(errorResult);
            resp.getWriter().write(jsonError);
        }
    }
}